package com.xmxsuperstar.app.forward;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.xmxsuperstar.app.CommonConstants;
import com.xmxsuperstar.app.Loggers;

public class ForwardServer {

	private static Logger logger = Loggers.defaultLogger;

	public static void main(String[] args) {
		ServerSocket sSocket = null;
		try {
			sSocket = new ServerSocket(10000);
			sSocket.setSoTimeout(20000);

			logger.info("Socket server is listing on:=" + 10000);

			while (true) {
				Socket socket = null;
				try {
					socket = sSocket.accept();
				} catch (SocketTimeoutException ste) {
					continue;
				}
				if (socket != null) {
					Thread localProxyProcessThread = new Thread(
							new LocalProxyProcessThread(socket));
					localProxyProcessThread.start();
				}
			}
		} catch (IOException e) {
			logger.error(e);
		}
	}

}

class LocalProxyProcessThread implements Runnable {

	private static Logger logger = Loggers.defaultLogger;

	Socket socket;

	public LocalProxyProcessThread(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		try {
			BufferedReader clientIn = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			PrintWriter clientOut = new PrintWriter(socket.getOutputStream(), true);

			String s = clientIn.readLine();
			logger.info("来自客户端的消息:" + s);
			
			Properties forwardProp = new Properties();
			
			forwardProp.load(ForwardServer.class
					.getResourceAsStream("/forward.properties"));

			String srv = forwardProp.getProperty("tunnel.server");
			
			Socket targetServer = new Socket(srv, 10000);
			targetServer.setSoTimeout(1000 * 60);
			BufferedReader targetIn = new BufferedReader(new InputStreamReader(
					targetServer.getInputStream()));
			PrintWriter targetOut = new PrintWriter(targetServer.getOutputStream(), true);
			
			targetOut.write(s + CommonConstants.CRLF);
			targetOut.flush();
			

			String response = targetIn.readLine();


			clientOut.write(response + CommonConstants.CRLF);
			clientOut.flush();

			logger.info("request end");
			clientIn.close();
			clientOut.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}